package cn.bjc.user.service.impl;

import cn.bjc.basic.constant.RegisterConstant;
import cn.bjc.basic.exception.BusinessException;
import cn.bjc.basic.jwt.JwtUtils;
import cn.bjc.basic.jwt.RsaUtils;
import cn.bjc.basic.util.HttpUtil;
import cn.bjc.basic.util.JsonResult;
import cn.bjc.basic.util.Md5Utils;
import cn.bjc.basic.util.StrUtils;
import cn.bjc.org.mapper.EmployeeMapper;
import cn.bjc.system.domain.Menu;
import cn.bjc.user.constant.WxConstants;
import cn.bjc.user.domain.LoginData;
import cn.bjc.user.domain.Logininfo;
import cn.bjc.user.domain.User;
import cn.bjc.user.domain.WxUser;
import cn.bjc.user.dto.LoginDto;
import cn.bjc.user.dto.WxDto;
import cn.bjc.user.mapper.LogininfoMapper;
import cn.bjc.user.mapper.UserMapper;
import cn.bjc.user.mapper.WxUserMapper;
import cn.bjc.user.service.ILoginService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.Permission;
import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements ILoginService {
    
    @Autowired
    private LogininfoMapper logininfoMapper;
    
    @Autowired
    private RedisTemplate redisTemplate;
    
    @Autowired
    private WxUserMapper wxUserMapper;
    
    @Autowired
    private UserMapper userMapper;
    
    
    @Autowired
    private EmployeeMapper employeeMapper;
    
    
    @Override
    public Map<String, Object> account(LoginDto dto) {
        /**思路:
         * 1.根据手机号/邮箱和type查询Logininfo
         * 2.如果存在,则判断密码是否正确
         *  2.1加密的,     (你输入的密码+数据库的盐值)md5加密
         * 3.如果不存在,则提示,用户名不存在
         */
        
        //1.根据手机号/邮箱和type查询Logininfo
        Logininfo logininfo = logininfoMapper.getLogininfoByDto(dto);
        if(logininfo==null){
            throw new BusinessException("账号或密码错误");
        }
        
        //判断密码是否正确  加盐加密;
        String md5Password = Md5Utils.encrypByMd5(logininfo.getSalt() + dto.getPassword());

        //和数据库中的做对比
        if(!md5Password.equals(logininfo.getPassword())){
            throw new BusinessException("账号或密码错误");
        }
        
        //把数据保存在redis中,并设置保持时间
        ////随机生成一个UUID(36位,一般情况不会重复)
        //String token = UUID.randomUUID().toString();
        ////设置30分钟过期
        //redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
        //
        ////准备一个map
        //HashMap<String,Object> map = new HashMap<>();
        //
        ////将数据放入map中
        //map.put("token", token);
        ////把盐值和密码设置为null,不给前台展示
        //logininfo.setSalt(null);
        //logininfo.setPassword(null);
        //map.put("logininfo", logininfo);
        
        //使用jwt
        Map<String,Object> map = loginSuccessJwtHandler(logininfo);
        
        //返回map
        return map;
    }

    private Map<String, Object> loginSuccessJwtHandler(Logininfo logininfo) {
        try {
            //创建一个LoginData对象(存放的是 logininfo,permissions,menus)
            LoginData loginData = new LoginData();
            //将logininfo信息添加进loginData内
            loginData.setLogininfo(logininfo);
            //创建一个新的Map
            Map<String,Object> map = new HashMap<>();
            
            //判断登陆人员是否是管理人员
            if(logininfo.getType()==0){//管理人员
                
                //通过logininfo的logininfo_id,查询取得当前登录人的权限permissions
                List<String> permissions = employeeMapper.getPermissionsByLogininfoId(logininfo.getId());
                
                //通过logininfo的logininfo_id,查询取得当前登录人的所有的菜单menus
                List<Menu> menus = employeeMapper.getMenusByLogininfoId(logininfo.getId());
                
                //将permissions和menus数据存入LoginData
                loginData.setPermissions(permissions);
                loginData.setMenus(menus);

                //将当前登陆人的权限和菜单添加到map - 响应给前端
                map.put("permissions",permissions);
                map.put("menus",menus);
            }
            //加密
            //通过私钥对登录信息进行加密 - jwtToken串
            PrivateKey privateKey = RsaUtils.getPrivateKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            //将登陆人信息加密得到jwtToken串(参数一:要加密的数据,参数二:加密的密钥,参数三:时间,单位Minutes分钟)
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 300);
            
            //5.将jwtToken和logininfo装到map返回
            map.put("token",jwtToken);
            map.put("logininfo",logininfo);
            
            return map;
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //微信登录
    @Override
    public JsonResult weChat(String code) {
        /**
         * 思路分析:
         * 之前有没有绑定过
         *  1.先根据code查询出token和openid
         *  2.根据openid查询
         *  3.openid存在,说明之前有绑定过:直接免密登录
         *  
         *  如果openid不存在,就要重新生成数据,绑定
         */
        String jsonStr = HttpUtil.httpGet(WxConstants.GET_ACK_URL
                .replace("APPID", WxConstants.APPID)
                .replace("SECRET", WxConstants.SECRET)
                .replace("CODE", code));
        
        //获取token和openid
        //把json字符串转成json对象
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");

        System.out.println(access_token);
        //根据openid查询wxuser
        WxUser dbWxUser = wxUserMapper.loadByOpenid(openid);
        //如果wxuser不为空,并且绑定了用户
        if (dbWxUser!=null && dbWxUser.getUser_id()!=null){
            //直接免密登录
            
            //获取logininfo信息
            Logininfo logininfo = logininfoMapper.loadByUserId(dbWxUser.getUser_id());
            
            ////随机生成一个UUID(36位,一般情况不会重复)
            //String token = UUID.randomUUID().toString();
            //
            ////设置30分钟过期
            //redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
            //
            ////准备一个map
            //HashMap<String,Object> map = new HashMap<>();
            //
            ////将数据放入map中
            //map.put("token", token);
            ////把盐值和密码设置为null,不给前台展示
            //logininfo.setSalt(null);
            //logininfo.setPassword(null);
            //map.put("logininfo", logininfo);

            //使用jwt
            Map<String,Object> map = loginSuccessJwtHandler(logininfo);

            //controller
            return JsonResult.me().setResultObj(map);
        }else { //第一次扫码
            //
            String param = "?accessToken="+access_token+"&openId="+openid;
            return JsonResult.me().setMsg("绑定").setResultObj(param);
        }
        
    }
    
    //微信绑定
    @Override
    public JsonResult binder(WxDto dto) {
        String phone = dto.getPhone();
        String verifyCode = dto.getVerifyCode();
        String accessToken = dto.getAccessToken();
        String openId = dto.getOpenId();
        
        //1.校验  非空校验,验证码超时校验,验证码是否正确校验
        if(StringUtils.isEmpty(phone)
        ||StringUtils.isEmpty(verifyCode)
        ||StringUtils.isEmpty(accessToken)
        ||StringUtils.isEmpty(openId))
        {
            throw new BusinessException("参数不能为空");
        }
        
        //校验验证码
        Object obj = redisTemplate.opsForValue().get(phone + RegisterConstant.WXBINDER);
        if(obj==null){
            throw new BusinessException("验证码过期,请重新获取");
        }
        if(!verifyCode.equalsIgnoreCase(obj.toString().split(":")[0])){
            throw new BusinessException("验证码错误,请重新输入");
        }
        //2.三张表: wxuser,user,logininfo
        
        //3.向微信开放平台发送第三次请求,获取wxuser信息
        String jsonObj = HttpUtil.httpGet(WxConstants.GET_WxUSER_URL
                .replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId)
                );
        
        //获取wxuser
        WxUser wxUser = jsonObj2WxUser(jsonObj);
        
        //通过手机号查询user信息,能查到:和直接绑定
        User dbUser = userMapper.findByPhone(phone);

        //通过手机号查询user信息,查不到,自己生成一个user,logininfo信息,在绑定
        if (dbUser==null) {
            //没有用手机号注册过,生成有个user对象,存值,并关联一个logininfo
            dbUser = phone2User(phone);
            //logininfo
            Logininfo dblogininfo = user2Logininfo(dbUser);
            //保存logininfo,返回自增长主键
            logininfoMapper.save(dblogininfo);
            
            //保存user    把logininfo_id放进去
            dbUser.setLogininfo_id(dblogininfo.getId());
            userMapper.save(dbUser);
        }
        
        //绑定wxuser
        wxUser.setUser_id(dbUser.getId());
        wxUserMapper.save(wxUser);
        
        //通过user中的logininfoid查询logininfo
        Logininfo logininfo = logininfoMapper.loadById(dbUser.getLogininfo_id());
        
        ////免密登录
        ////随机生成一个UUID(36位,一般情况不会重复)
        //String token = UUID.randomUUID().toString();
        ////设置30分钟过期
        //redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
        //
        ////准备一个map
        //HashMap<String,Object> map = new HashMap<>();
        //
        ////将数据放入map中
        //map.put("token", token);
        ////把盐值和密码设置为null,不给前台展示
        //logininfo.setSalt(null);
        //logininfo.setPassword(null);
        //map.put("logininfo", logininfo);

        //使用jwt
        Map<String,Object> map = loginSuccessJwtHandler(logininfo);
        
        //往controller层
        return JsonResult.me().setResultObj(map);
        
    }

    //生成一个logininfo对象
    private Logininfo user2Logininfo(User dbUser) {

        Logininfo logininfo = new Logininfo();
        //设置type=1: 普通用户
        logininfo.setType(1);
        BeanUtils.copyProperties(dbUser, logininfo);
        
        return logininfo;
    }

    //生成一个user对象
    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        //生成盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        
        //生成密码
        String password = StrUtils.getComplexRandomString(6);
        
        //加密
        String dbPassword = Md5Utils.encrypByMd5(salt + password);
        user.setPassword(dbPassword);
        
        return user;
    }


    //返回一个wxuser对象
    private WxUser jsonObj2WxUser(String jsonObj) {
        /*
        {
            "openid":"OPENID",
            "nickname":"NICKNAME",
            "sex":1,
            "province":"PROVINCE",
            "city":"CITY",
            "country":"COUNTRY",
            "headimgurl": "http://wx.qlogo.cn/mmopen/....../0",
            "privilege":[
                        "PRIVILEGE1",
                        "PRIVILEGE2"
                        ],
            "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"
        }
         */
        //把jsonObj转成json对象
        JSONObject jsonObject = JSONObject.parseObject(jsonObj);
        
        WxUser wxUser = new WxUser();
        wxUser.setAddress(jsonObject.getString("country"));
        wxUser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxUser.setNickname(jsonObject.getString("nickname"));//昵称,怕有特殊字符可改为"XX"
        wxUser.setOpenid(jsonObject.getString("openid"));
        wxUser.setSex(jsonObject.getInteger("sex"));
        wxUser.setUnionid(jsonObject.getString("unionid"));
        
        return wxUser;
    }
}
